<script>

/**
 * 使用示例
 * <date-time-picker prompt="请输入故障日期" @change="onGzDateChange"></date-time-picker>
 *
 * 当数值发生change事件时调用
 * onGzDateChange(e){
 *   console.log(e);
 *   // 返回的数值 2024-01-01 15:00:00,不记录秒，秒总是00
 * }
 */
export default {
  name: "dateTimePicker",
  props: {
    prompt: {
      type: String,
      default: '请选择日期时间'
    },
    //默认时间格式 2024-01-01 15:00:01
    defaultTime :{
      type: String,
      default: '',
    }
  },
  data() {
    const date = new Date();
    const years = [];
    const months = [];
    const days = [];
    const hours = [];
    const minutes = [];
    // 获取年
    for (let i = date.getFullYear() - 5; i <= date.getFullYear() + 5; i++) {
      years.push(i + '年');
    }
    // 获取月
    for (let i = 1; i <= 12; i++) {
      months.push(i + '月');
    }
    // 获取日
    for (let i = 1; i <= 31; i++) {
      days.push(i + '日');
    }
    // 获取时
    for (let i = 0; i <= 23; i++) {
      hours.push(i + '时');
    }
    // 获取分
    for (let i = 0; i <= 59; i++) {
      minutes.push(i + '分');
    }
    let defaultTimeArray = null;
    if (this.defaultTime){
      const date = new Date(this.defaultTime);
      const year = date.getFullYear();
      const month = date.getMonth();
      const day = date.getDate();
      const hour = date.getHours();
      const minute = date.getMinutes();
      defaultTimeArray = [years.indexOf(year+'年'), month, day - 1, hour, minute];
    }
    return {
      // 年月日时分的索引数组
      dateTime: defaultTimeArray || [years.indexOf(date.getFullYear()+'年'), date.getMonth(),date.getDate() - 1, date.getHours(),date.getMinutes()],
      // 年月日时分的数据数组
      dateTimeArray: [years, months, days, hours, minutes],
      time: null,
    };
  },
  methods: {
    // 日期时间选择器值变化事件
    onDateTimePickerChange(e) {
      const dateTimeArray = this.dateTimeArray;
      const dateTime = e.detail.value;
      const year = (dateTimeArray[0][dateTime[0]]).substring(0,4);
      const month = (dateTimeArray[1][dateTime[1]]).padStart(3,'0').substring(0,2);
      const day = (dateTimeArray[2][dateTime[2]]).padStart(3,'0').substring(0,2);
      const hour = (dateTimeArray[3][dateTime[3]]).padStart(3,'0').substring(0,2);
      const minute = (dateTimeArray[4][dateTime[4]]).padStart(3,'0').substring(0,2);
      this.time = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.$emit('change', this.time);
    },
  }
}
</script>

<template>
  <view >
    <picker mode="multiSelector"
            :value='dateTime'
            :range="dateTimeArray"
            @change="onDateTimePickerChange"
            >
      <view class="text">
        {{ time || prompt }}
      </view>
    </picker>
  </view>
</template>

<style scoped lang="scss">

</style>
